package com.example.administrator.kotiln.ui;


import android.Manifest;
import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;

import android.support.v7.app.AppCompatActivity;

import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.administrator.kotiln.R;
import com.example.administrator.kotiln.base.BaseActivity;
import com.example.administrator.kotiln.bean.Test_Socket_Data;

import com.example.administrator.kotiln.utils.AppManager;
import com.example.administrator.kotiln.utils.DateUtils;
import com.example.administrator.kotiln.utils.SPUtils;
import com.example.administrator.kotiln.utils.Share;
import com.example.administrator.kotiln.utils.ToastUtils;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import de.tavendo.autobahn.WebSocketConnection;
import de.tavendo.autobahn.WebSocketException;
import de.tavendo.autobahn.WebSocketHandler;
import me.weyye.hipermission.HiPermission;
import me.weyye.hipermission.PermissionCallback;
import me.weyye.hipermission.PermissionItem;

import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE;

/**
 * Created by Administrator on 2017/9/29.
 */

public class SocketTwoActivity extends BaseActivity implements View.OnClickListener {

    private Button socket_bt;
    private TextView socket_msg;
    private EditText socket_send;
    private String resultmessage;
    private Button hi;
    private Button his;
    private String s1;
    private WebSocketConnection mConnect = new WebSocketConnection();


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sockecttwo);

        initView();
        initSocket();


    }

    @Override
    protected void onRestart() {
        super.onRestart();
    }

    private void initView() {
        socket_bt = (Button) findViewById(R.id.socket_bt);
        socket_msg = (TextView) findViewById(R.id.socket_msg);
        socket_send = (EditText) findViewById(R.id.socket_send);
        hi = (Button) findViewById(R.id.hi);
        his = (Button) findViewById(R.id.his);
        ImageView back = (ImageView) findViewById(R.id.back);

        //返回按钮
        back.setOnClickListener(this);
        socket_bt.setOnClickListener(this);
        hi.setOnClickListener(this);
        his.setOnClickListener(this);

//        if (mConnect.isConnected()){
//            ToastUtils.showToast(SocketTwoActivity.this,"链接");
//        }else {
//            ToastUtils.showToast(SocketTwoActivity.this,"为链接");
//        }


    }


    String url = "ws://192.168.1.240:9505/";

    public void initSocket() {
        Share.d("执行了链接");
        try {
            mConnect.connect(url, new WebSocketHandler() {

                @Override
                public void onOpen() {
                    Log.i("TAG", "onOpen: ");
                    ToastUtils.showToast(SocketTwoActivity.this, "onOpen");
                }

                @Override
                public void onTextMessage(String payload) {
                    Log.i("TAG", "onTextMessage: " + payload);
                    resultmessage = payload;
//
//                    ToastUtils.showToast(SocketTwoActivity.this, "isConnected");
//
//                    socket_msg.append("client:" + resultmessage + "\n");
//
//                    Share.d("返回数据a" + resultmessage);
//
//
//                    resultmessage = "";
//                    Share.d("清理后的数据" + "=null" + resultmessage);
                    handler.sendEmptyMessage(0);


                    //handler.sendEmptyMessage(0);

                }

                @Override
                public void onClose(int code, String reason) {
                    Log.i("TAG", "onClose: " + code + "|" + reason);
                    ToastUtils.showToast(SocketTwoActivity.this, "没有连接上服务器");
                }
            });
        } catch (WebSocketException e) {
            e.printStackTrace();
        }
    }


    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.socket_bt:
                //获取当前时间
                s1 = DateUtils.getCurrentTime_Today();
                socket_send.setText(s1);
                String send = socket_send.getText().toString();
                String message = "test";

                List<Test_Socket_Data> list = new ArrayList<Test_Socket_Data>();
                list.add(new Test_Socket_Data(send, message));
                Gson gson = new Gson();
                String line = gson.toJson(list);
                SPUtils.put(SocketTwoActivity.this, "data", line);
                String to = (String) SPUtils.get(SocketTwoActivity.this, "data", "");
                //Share.d("数据" + to);
                if (mConnect.isConnected()) {
                    mConnect.sendTextMessage(line);
                    ToastUtils.showToast(SocketTwoActivity.this, "连接上服务器");
                } else {
                    ToastUtils.showToast(SocketTwoActivity.this, "没有连接上服务器");
                }

                break;
            case R.id.hi:
                hipermission();
                break;
            case R.id.his:
                hipermissions();
                break;
            default:
                break;
        }

    }

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:

                    ToastUtils.showToast(SocketTwoActivity.this, "isConnected");

                    socket_msg.append("client:" + resultmessage + "\n");

                    Share.d("返回数据a" + resultmessage);


                    resultmessage = "";
                    Share.d("清理后的数据" + "=null" + resultmessage);

                    break;
                default:
                    break;
            }
        }
    };


    private void hipermissions() {
        List<PermissionItem> permissionItems = new ArrayList<PermissionItem>();
        permissionItems.add(new PermissionItem(Manifest.permission.READ_PHONE_STATE, "手机状态", R.drawable.permission_ic_phone));
        permissionItems.add(new PermissionItem(Manifest.permission.CAMERA, "照相机", R.drawable.permission_ic_location));
        permissionItems.add(new PermissionItem(Manifest.permission.ACCESS_FINE_LOCATION, "定位", R.drawable.permission_ic_location));
        permissionItems.add(new PermissionItem(Manifest.permission.CALL_PHONE, "打电话", R.drawable.permission_ic_location));
        permissionItems.add(new PermissionItem(Manifest.permission.WRITE_EXTERNAL_STORAGE, "存储权限", R.drawable.permission_ic_location));
        HiPermission.create(SocketTwoActivity.this)
                .title(getString(R.string.permission_cus_title))
                .permissions(permissionItems)
                .msg(getString(R.string.permission_cus_msg))
                //默认的主题显示风格
                //.animStyle(R.style.PermissionAnimFade)
                //自定义的主题显示风格
                .animStyle(R.style.PermissionAnimScale)
                .style(R.style.PermissionDefaultBlueStyle)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {

                        showToast(getString(R.string.permission_on_close));
                    }

                    @Override
                    public void onFinish() {
                        showToast(getString(R.string.permission_completed));
                    }

                    @Override
                    public void onDeny(String permission, int position) {

                    }

                    @Override
                    public void onGuarantee(String permission, int position) {

                    }
                });
    }


    private void hipermission() {
        HiPermission.create(SocketTwoActivity.this)
                .animStyle(R.style.PermissionAnimFade)
                .checkMutiPermission(new PermissionCallback() {
                    @Override
                    public void onClose() {
                        Log.i("TAG", "onClose");
                        showToast(getString(R.string.permission_on_close));
                    }

                    @Override
                    public void onFinish() {
                        showToast(getString(R.string.permission_completed));
                    }

                    @Override
                    public void onDeny(String permission, int position) {
                        Log.i("TAG", "onDeny");
                    }

                    @Override
                    public void onGuarantee(String permission, int position) {
                        Log.i("TAG", "onGuarantee");
                    }
                });
    }

    private void showToast(String text) {
        Toast.makeText(SocketTwoActivity.this, text, Toast.LENGTH_SHORT).show();
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mConnect.isConnected()) {
            mConnect.disconnect();
            ToastUtils.showToast(SocketTwoActivity.this, "关闭了页面和链接");
        }
        // AppManager.getAppManager().finishActivity(SocketTwoActivity.this);
    }


}
